package com.codebase.zookeeper.zk;

import org.apache.zookeeper.AsyncCallback;
import org.apache.zookeeper.CreateMode;
import org.apache.zookeeper.WatchedEvent;
import org.apache.zookeeper.Watcher;
import org.apache.zookeeper.ZooDefs;
import org.apache.zookeeper.ZooKeeper;
import org.apache.zookeeper.data.Stat;
import org.junit.Test;

import java.util.concurrent.CountDownLatch;

/**
 * 获取节点数据
 */
public class GetData implements Watcher {

    private static CountDownLatch countDownLatch = new CountDownLatch(1);
    private static ZooKeeper zk = null;
    private static Stat stat = new Stat();

    @Override
    public void process(WatchedEvent event) {
        if(event.getState() == Event.KeeperState.SyncConnected){
            if(Event.EventType.None == event.getType() && null == event.getPath()){
                countDownLatch.countDown();
            } else if(event.getType() == Event.EventType.NodeDataChanged){  //节点的数据改变
                try {
                    System.out.println("节点的数据改变：" + new String(zk.getData(event.getPath(), true, stat)));
                    System.out.println(stat.getCzxid() + "  " + stat.getMzxid() + "  "+ stat.getVersion());
                }catch (Exception e){
                    e.printStackTrace();
                }
            }
        }
    }

    /**
     * 同步方式获取节点的数据
     * @throws Exception
     */
    @Test
    public void test1() throws Exception {
        String path = "/root";
        zk = new ZooKeeper("127.0.0.1:2181", 5000, new GetData());
        countDownLatch.await();
        zk.create(path, "12".getBytes(), ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.EPHEMERAL);
        System.out.println(zk.getData(path, true, stat));
        zk.setData(path, "1212".getBytes(), -1);
        Thread.sleep(3000);
    }

    /**
     * 异步方式获取节点的数据
     * @throws Exception
     */
    @Test
    public void test2() throws Exception{
        String path = "/root";
        zk = new ZooKeeper("127.0.0.1:2181", 5000, new GetData());
        countDownLatch.await();
        zk.create(path, "12".getBytes(), ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.EPHEMERAL);
        zk.getData(path, true, new MyDataCallBack(), "ctx");
        zk.setData(path, "1212".getBytes(), -1);
        Thread.sleep(3000);
    }

    class MyDataCallBack implements AsyncCallback.DataCallback{
        @Override
        public void processResult(int rc, String path, Object ctx, byte[] data, Stat stat) {
            System.out.println("数据是" + data);
        }
    }

}
